package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.dto.ArticleFavoriteDTO;
import com.example.entity.Article;
import com.example.entity.ArticleFavorite;
import com.example.entity.Tag;
import com.example.mapper.ArticleFavoriteMapper;
import com.example.mapper.ArticleMapper;
import com.example.mapper.ArticleTagRelMapper;
import com.example.mapper.TagMapper;
import com.example.service.ArticleFavoriteService;
import com.example.vo.ArticlePageVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 文章收藏服务实现类
 */
@Slf4j
@Service
public class ArticleFavoriteServiceImpl implements ArticleFavoriteService {

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private ArticleFavoriteMapper articleFavoriteMapper;
    
    @Resource
    private TagMapper tagMapper;
    
    @Resource
    private ArticleTagRelMapper articleTagRelMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean toggleFavorite(ArticleFavoriteDTO articleFavoriteDTO, Integer userId) {
        if (articleFavoriteDTO == null || articleFavoriteDTO.getArticleId() == null || userId == null) {
            log.error("收藏文章参数错误: articleId={}, userId={}",
                    articleFavoriteDTO != null ? articleFavoriteDTO.getArticleId() : "null", userId);
            return false;
        }

        Integer articleId = articleFavoriteDTO.getArticleId();
        boolean hasFavorited = hasFavorited(articleId, userId);

        try {
            // 获取文章
            Article article = articleMapper.selectById(articleId);
            if (article == null) {
                log.error("文章不存在: articleId={}", articleId);
                return false;
            }

            Integer favoriteCount = article.getFavoriteCount();
            if (favoriteCount == null) {
                favoriteCount = 0;
            }

            if (hasFavorited) {
                // 已收藏，取消收藏
                try {
                    LambdaQueryWrapper<ArticleFavorite> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(ArticleFavorite::getArticleId, articleId)
                           .eq(ArticleFavorite::getUserId, userId);
                    articleFavoriteMapper.delete(wrapper);

                    // 更新收藏数
                    article.setFavoriteCount(Math.max(favoriteCount - 1, 0));
                    articleMapper.updateById(article);

                    log.info("用户[{}]取消收藏文章[{}]成功，当前收藏数: {}", userId, articleId, article.getFavoriteCount());
                    return false; // 返回false表示当前未收藏
                } catch (Exception e) {
                    log.error("取消收藏失败: articleId={}, userId={}, error={}", articleId, userId, e.getMessage(), e);
                    throw e;
                }
            } else {
                // 未收藏，添加收藏
                try {
                    ArticleFavorite favorite = new ArticleFavorite();
                    favorite.setArticleId(articleId);
                    favorite.setUserId(userId);
                    favorite.setCreateTime(LocalDateTime.now());
                    articleFavoriteMapper.insert(favorite);

                    // 更新收藏数
                    article.setFavoriteCount(favoriteCount + 1);
                    articleMapper.updateById(article);

                    log.info("用户[{}]收藏文章[{}]成功，当前收藏数: {}", userId, articleId, article.getFavoriteCount());
                    return true; // 返回true表示当前已收藏
                } catch (Exception e) {
                    log.error("收藏失败: articleId={}, userId={}, error={}", articleId, userId, e.getMessage(), e);
                    throw e;
                }
            }
        } catch (Exception e) {
            log.error("处理文章收藏操作异常: articleId={}, userId={}, error={}", articleId, userId, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public boolean hasFavorited(Integer articleId, Integer userId) {
        if (articleId == null || userId == null) {
            return false;
        }

        try {
            Integer count = articleFavoriteMapper.checkUserFavorite(articleId, userId);
            return count != null && count > 0;
        } catch (Exception e) {
            // 如果表不存在等异常情况，返回false
            log.error("查询用户收藏状态异常: articleId={}, userId={}, error={}", articleId, userId, e.getMessage());
            return false;
        }
    }
    
    @Override
    public IPage<ArticlePageVO> getUserFavoriteArticles(Integer userId, int pageNum, int pageSize) {
        Page<ArticlePageVO> page = new Page<>(pageNum, pageSize);
        
        try {
            // 查询用户收藏的文章
            IPage<ArticlePageVO> articlePage = articleFavoriteMapper.getUserFavoriteArticles(page, userId);
            
            // 如果没有收藏记录，直接返回空列表
            if (articlePage.getRecords().isEmpty()) {
                return articlePage;
            }
            
            // 查询文章标签信息
            for (ArticlePageVO article : articlePage.getRecords()) {
                try {
                    // 查询文章标签
                    List<Tag> tags = tagMapper.getTagsByArticleId(article.getId());
                    article.setTags(tags);
                } catch (Exception e) {
                    log.error("查询文章标签信息异常: {}", e.getMessage());
                    // 设置空标签列表，不影响整体结果
                    article.setTags(List.of());
                }
            }
            
            return articlePage;
            
        } catch (Exception e) {
            log.error("获取用户收藏文章列表异常: {}", e.getMessage(), e);
            return page;
        }
    }
}